/*
 * Copyright 2016 requery.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.requery.ohos.example.app.slice;

import io.requery.ohos.QueryAdapter;
import io.requery.ohos.example.app.PeopleApplication;
import io.requery.ohos.example.app.ResourceTable;
import io.requery.ohos.example.app.model.Models;
import io.requery.ohos.example.app.model.PersonEntity;
import io.requery.ohos.example.app.utils.LogUtil;
import io.requery.ohos.example.app.utils.ResUtil;
import io.requery.query.Result;
import io.requery.Persistable;
import io.requery.ohos.example.app.model.Person;
import io.requery.reactivex.ReactiveEntityStore;

import ohos.aafwk.content.Intent;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Image;
import ohos.agp.utils.Color;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Activity displaying a list of random people. You can tap on a person to edit their record.
 * Shows how to use a query with a { ListContainer} and { QueryAdapter} and RxJava
 */
public class PeopleActivity extends AbilitySlice {
    private ReactiveEntityStore<Persistable> data;
    private ExecutorService executor;
    private PersonAdapter adapter;

    private ListContainer listContainer;
    private Text add;
    private String TAG = PeopleActivity.class.getName();

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_listcont);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_sample_list);
        add = (Text) findComponentById(ResourceTable.Id_optionMenu);
        data = ((PeopleApplication) getAbility()).getData();
        adapter = new PersonAdapter();
        listContainer.setItemProvider(adapter);
        adapter.queryAsync();

        add.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                present(new PersonEditActivity(), intent1);
            }
        });
    }

    @Override
    protected void onActive() {
        adapter.queryAsync();
        super.onActive();
    }

    @Override
    protected void onStop() {
        adapter.close();
        super.onStop();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    /**
     * PersonAdapter
     */
    public class PersonAdapter extends QueryAdapter<Person> implements Component.ClickedListener {
        private final Random random = new Random();
        private final Color[] colors = { Color.RED, Color.BLUE, Color.GREEN, Color.MAGENTA,
                Color.DKGRAY, Color.CYAN, Color.BLACK};

        public PersonAdapter() {
            super(Models.DEFAULT, Person.class);
        }

        @Override
        public Result<Person> performQuery() {
            return data.select(Person.class).orderBy(PersonEntity.NAME.lower()).get();
        }

        @Override
        public int getPersonCount() {
            int count  = data.count(Person.class).get().value();
            return count;
        }

        @Override
        public Component getComponent(Person item, Component convertView, ComponentContainer parent) {
            final Component cpt;
            if (convertView == null) {
                cpt = LayoutScatter.getInstance(parent.getContext())
                        .parse(ResourceTable.Layout_person_item, null, false);
            } else {
                cpt = convertView;
            }

            Image img = (Image) cpt.findComponentById(ResourceTable.Id_image_color);
            Text text = (Text) cpt.findComponentById(ResourceTable.Id_name_person);

            if (item.getName() != null) {
                img.setBackground(ResUtil.getCustomRectGradientDrawable(colors[random.nextInt(colors.length)]));
                text.setText(item.getName());
            }
            cpt.setTag(item);
            cpt.setClickedListener(this);
            return cpt;
        }

        @Override
        public void onClick(Component component) {
            Person person = (Person) component.getTag();
            Intent intent = new Intent();
            intent.setParam(PersonEditActivity.EXTRA_PERSON_ID, person.getId());
            present(new PersonEditActivity(), intent);
        }
    }
}
